package com.wxw.demo.service;

import com.wxw.demo.bean.Comment;
import com.wxw.demo.dao.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author wxw
 * @data 2020/9/7 16 :45
 * @description
 */
@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;
   @Autowired
   private RedisTemplate redisTemplate;

    public Comment finById(int comment_id){
        Object object = redisTemplate.opsForValue().get("comment_" + comment_id);
        Date date = new Date();
      
        if (object!=null){
            return (Comment)object;
        }else {

            Optional<Comment> optional = commentRepository.findById(comment_id);
            if (optional.isPresent()){

                Comment comment = optional.get();

                //将查询结果进行缓存，并设置有效期为1天
                redisTemplate.opsForValue().set("comment_"+comment_id,comment,1, TimeUnit.DAYS);
                return comment;
            }else {
                return  null;
            }
        }

    }

    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(),comment.getAId());
        //更新数据后进行缓存
        redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);
        return comment;
    }

    public void deleteComment(int comment_id){
        commentRepository.deleteById(comment_id);
        //删除后进行缓存删除
        redisTemplate.delete("comment_"+comment_id);
    }
}
